package org.jeecg.hr.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.autopoi.poi.excel.ExcelImportUtil;
import org.jeecg.autopoi.poi.excel.def.NormalExcelConstants;
import org.jeecg.autopoi.poi.excel.entity.ExportParams;
import org.jeecg.autopoi.poi.excel.entity.ImportParams;
import org.jeecg.autopoi.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.hr.entity.InsuranceTemplate;
import org.jeecg.hr.entity.InsuranceTemplateDetail;
import org.jeecg.hr.service.InsuranceTemplateDetailService;
import org.jeecg.hr.service.InsuranceTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 社保方案
 * @Author: MxpIO
 */
@Api(tags = "社保方案")
@RestController
@RequestMapping("/hr/insurance/template")
@Slf4j
public class InsuranceTemplateController extends JeecgController<InsuranceTemplate, InsuranceTemplateService> {

	@Autowired
	private InsuranceTemplateService insuranceTemplateService;

	@Autowired
	private InsuranceTemplateDetailService insuranceTemplateDetailService;

	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * 
	 * @param insuranceTemplate
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "社保方案-分页列表查询")
	@ApiOperation(value = "社保方案-分页列表查询", notes = "社保方案-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(InsuranceTemplate insuranceTemplate,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		QueryWrapper<InsuranceTemplate> queryWrapper = QueryGenerator.initQueryWrapper(insuranceTemplate,
				req.getParameterMap());
		Page<InsuranceTemplate> page = new Page<InsuranceTemplate>(pageNo, pageSize);
		IPage<InsuranceTemplate> pageList = insuranceTemplateService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 * 
	 * @param insuranceTemplate
	 * @return
	 */
	@AutoLog(value = "社保方案-添加")
	@ApiOperation(value = "社保方案-添加", notes = "社保方案-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody InsuranceTemplate insuranceTemplate) {
		insuranceTemplateService.save(insuranceTemplate);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 * 
	 * @param insuranceTemplate
	 * @return
	 */
	@AutoLog(value = "社保方案-编辑")
	@ApiOperation(value = "社保方案-编辑", notes = "社保方案-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody InsuranceTemplate insuranceTemplate) {
		insuranceTemplateService.updateById(insuranceTemplate);
		return Result.OK("编辑成功!");
	}

	/**
	 * 添加
	 *
	 * @param insuranceTemplate
	 * @return
	 */
	@AutoLog(value = "社保方案-添加(主从)")
	@ApiOperation(value = "社保方案-添加(主从)", notes = "社保方案-添加(主从)")
	@PostMapping(value = "/addWithChildren")
	public Result<?> addWithChildren(@RequestBody InsuranceTemplate insuranceTemplate) {
		insuranceTemplateService.saveInsuranceTemplateWithDetail(insuranceTemplate);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param insuranceTemplate
	 * @return
	 */
	@AutoLog(value = "社保方案-编辑(主从)")
	@ApiOperation(value = "社保方案-编辑(主从)", notes = "社保方案-编辑(主从)")
	@PutMapping(value = "/editWithChildren")
	public Result<?> editWithChildren(@RequestBody InsuranceTemplate insuranceTemplate) {
		InsuranceTemplate insuranceTemplateEntity = insuranceTemplateService.getById(insuranceTemplate.getId());
		if (insuranceTemplateEntity == null) {
			return Result.error("未找到对应数据");
		}
		insuranceTemplateService.updateInsuranceTemplateWithDetail(insuranceTemplate);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "社保方案-通过id删除")
	@ApiOperation(value = "社保方案-通过id删除", notes = "社保方案-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		insuranceTemplateService.delInsuranceTemplate(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "社保方案-批量删除")
	@ApiOperation(value = "社保方案-批量删除", notes = "社保方案-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		this.insuranceTemplateService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, InsuranceTemplate insuranceTemplate) {
		return super.exportXls(request, insuranceTemplate, InsuranceTemplate.class, "社保方案");
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, InsuranceTemplate.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/

	/*--------------------------------子表处理-社保方案明细-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * 
	 * @return
	 */
	@AutoLog(value = "社保方案明细-通过templateCode查询")
	@ApiOperation(value = "社保方案明细-通过templateCode查询", notes = "社保方案明细-通过templateCode查询")
	@GetMapping(value = "/listInsuranceTemplateDetailByTemplateCode")
	public Result<?> listInsuranceTemplateDetailByMainId(InsuranceTemplateDetail insuranceTemplateDetail,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

		Object tamplate = req.getParameter("templateCode");
		if(tamplate == null){
			return Result.OK();
		}
		QueryWrapper<InsuranceTemplateDetail> queryWrapper = QueryGenerator.initQueryWrapper(insuranceTemplateDetail,
				req.getParameterMap());
		Page<InsuranceTemplateDetail> page = new Page<InsuranceTemplateDetail>(pageNo, pageSize);
		IPage<InsuranceTemplateDetail> pageList = insuranceTemplateDetailService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 * 
	 * @param insuranceTemplateDetail
	 * @return
	 */
	@AutoLog(value = "社保方案明细-添加")
	@ApiOperation(value = "社保方案明细-添加", notes = "社保方案明细-添加")
	@PostMapping(value = "/addInsuranceTemplateDetail")
	public Result<?> addInsuranceTemplateDetail(@RequestBody InsuranceTemplateDetail insuranceTemplateDetail) {
		insuranceTemplateDetailService.save(insuranceTemplateDetail);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 * 
	 * @param insuranceTemplateDetail
	 * @return
	 */
	@AutoLog(value = "社保方案明细-编辑")
	@ApiOperation(value = "社保方案明细-编辑", notes = "社保方案明细-编辑")
	@PutMapping(value = "/editInsuranceTemplateDetail")
	public Result<?> editInsuranceTemplateDetail(@RequestBody InsuranceTemplateDetail insuranceTemplateDetail) {
		insuranceTemplateDetailService.updateById(insuranceTemplateDetail);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "社保方案明细-通过id删除")
	@ApiOperation(value = "社保方案明细-通过id删除", notes = "社保方案明细-通过id删除")
	@DeleteMapping(value = "/deleteInsuranceTemplateDetail")
	public Result<?> deleteInsuranceTemplateDetail(@RequestParam(name = "id", required = true) String id) {
		insuranceTemplateDetailService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "社保方案明细-批量删除")
	@ApiOperation(value = "社保方案明细-批量删除", notes = "社保方案明细-批量删除")
	@DeleteMapping(value = "/deleteBatchInsuranceTemplateDetail")
	public Result<?> deleteBatchInsuranceTemplateDetail(@RequestParam(name = "ids", required = true) String ids) {
		this.insuranceTemplateDetailService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportInsuranceTemplateDetail")
	public ModelAndView exportInsuranceTemplateDetail(HttpServletRequest request,
			InsuranceTemplateDetail insuranceTemplateDetail) {
		// Step.1 组装查询条件
		QueryWrapper<InsuranceTemplateDetail> queryWrapper = QueryGenerator.initQueryWrapper(insuranceTemplateDetail,
				request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<InsuranceTemplateDetail> pageList = insuranceTemplateDetailService.list(queryWrapper);
		List<InsuranceTemplateDetail> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId()))
					.collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "社保方案明细"); // 此处设置的filename无效
																// ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, InsuranceTemplateDetail.class);
		mv.addObject(NormalExcelConstants.PARAMS,
				new ExportParams("社保方案明细报表", "导出人:" + sysUser.getRealname(), "社保方案明细"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importInsuranceTemplateDetail/{templateCode}")
	public Result<?> importInsuranceTemplateDetail(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("templateCode") String templateCode) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<InsuranceTemplateDetail> list = ExcelImportUtil.importExcel(file.getInputStream(),
						InsuranceTemplateDetail.class, params);
				for (InsuranceTemplateDetail temp : list) {
					temp.setTemplateCode(templateCode);
				}
				long start = System.currentTimeMillis();
				insuranceTemplateDetailService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.OK("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-社保方案明细-end----------------------------------------------*/
}
